package com.huang.controller;


import com.huang.pojo.*;
import com.huang.service.AdminService;
import com.huang.service.StudentService;
import com.huang.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

@Controller
public class FileController {

    @Autowired
    @Qualifier("AdminServiceImpl")
    private AdminService adminService;
    @Autowired
    @Qualifier("TeacherServiceImpl")
    private TeacherService teacherService;
    @Autowired
    @Qualifier("StudentServiceImpl")
    private StudentService studentService;

    //@RequestParam("file") 将name=file控件得到的文件封装成CommonsMultipartFile 对象
    //批量上传CommonsMultipartFile则为数组即可

    @RequestMapping("/upload")
    public String fileUpload(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException, IOException {

        //获取文件名 : file.getOriginalFilename();
        String uploadFileName = file.getOriginalFilename();

        //如果文件名为空，直接回到首页！
        if ("".equals(uploadFileName)) {
            return "adminLogin";
        }
        System.out.println("上传文件名 : " + uploadFileName);

        //上传路径保存设置
        String path = request.getServletContext().getRealPath("/upload");
        //如果路径不存在，创建一个
        File realPath = new File(path);
        if (!realPath.exists()) {
            realPath.mkdir();
        }
        System.out.println("上传文件保存地址：" + realPath);

        InputStream is = file.getInputStream(); //文件输入流
        OutputStream os = new FileOutputStream(new File(realPath, uploadFileName)); //文件输出流

        //读取写出
        int len = 0;
        byte[] buffer = new byte[1024];
        while ((len = is.read(buffer)) != -1) {
            os.write(buffer, 0, len);
            os.flush();
        }
        os.close();
        is.close();
        return "adminLogin";
    }

    //上传活动海报
    @RequestMapping("/teacher/uploadPhoto")
    public String uploadPhoto(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request, Model model, HttpSession session) throws IOException, IOException {

        Activity activity = (Activity) session.getAttribute("activityData");

        //获取文件名 : file.getOriginalFilename();
        String uploadFileName = file.getOriginalFilename();

        //如果文件名为空，直接回到首页！
        if ("".equals(uploadFileName)) {
            model.addAttribute("activityPhotoErrorMsg", "海报上传失败");
            return "redirect:/teacher/toAddActivityDetail";
        }
        System.out.println("上传文件名 : " + uploadFileName);

        //上传路径保存设置
        String path = request.getServletContext().getRealPath("/upload/"+activity.getActivityNo());
        //如果路径不存在，创建一个
        File realPath = new File(path);
        if (!realPath.exists()) {
            realPath.mkdir();
        }
        System.out.println("上传文件保存地址：" + realPath);

        InputStream is = file.getInputStream(); //文件输入流
        OutputStream os = new FileOutputStream(new File(realPath, uploadFileName)); //文件输出流

        //读取写出
        int len = 0;
        byte[] buffer = new byte[1024];
        while ((len = is.read(buffer)) != -1) {
            os.write(buffer, 0, len);
            os.flush();
        }
        os.close();
        is.close();

        ActivityDescription activityDescription = teacherService.findActivityDescriptionByNo(activity);
        activityDescription.setActivityPhoto("/upload/"+activity.getActivityNo()+"/" + uploadFileName);
        activityDescription.setPhotoName(uploadFileName);
        if (teacherService.addActivityPhotoByNo(activityDescription) != 0) {
            model.addAttribute("activityPhotoRightMsg", "海报上传成功");

        } else {
            model.addAttribute("activityPhotoErrorMsg", "海报上传失败");
        }
        return "redirect:/teacher/toAddActivityDetail";
    }

    //上传活动附件
    @RequestMapping("/teacher/uploadAnnex")
    public String uploadAnnex(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request, Model model, HttpSession session) throws IOException, IOException {

        Activity activity = (Activity) session.getAttribute("activityData");

        //获取文件名 : file.getOriginalFilename();
        String uploadFileName = file.getOriginalFilename();

        //如果文件名为空，直接回到首页！
        if ("".equals(uploadFileName)) {
            model.addAttribute("activityAnnexErrorMsg", "附件上传失败");
            return "redirect:/teacher/toAddActivityDetail";
        }
        System.out.println("上传文件名 : " + uploadFileName);

        //上传路径保存设置
        String path = request.getServletContext().getRealPath("/upload/"+activity.getActivityNo());
        //如果路径不存在，创建一个
        File realPath = new File(path);
        if (!realPath.exists()) {
            realPath.mkdir();
        }
        System.out.println("上传文件保存地址：" + realPath);

        InputStream is = file.getInputStream(); //文件输入流
        OutputStream os = new FileOutputStream(new File(realPath, uploadFileName)); //文件输出流

        //读取写出
        int len = 0;
        byte[] buffer = new byte[1024];
        while ((len = is.read(buffer)) != -1) {
            os.write(buffer, 0, len);
            os.flush();
        }
        os.close();
        is.close();


        ActivityDescription activityDescription = teacherService.findActivityDescriptionByNo(activity);
        activityDescription.setActivityAnnex("/upload/"+activity.getActivityNo()+"/" + uploadFileName);
        activityDescription.setAnnexName(uploadFileName);
        if (teacherService.addActivityAnnexByNo(activityDescription) != 0) {
            model.addAttribute("activityAnnexRightMsg", "附件上传成功");

        } else {
            model.addAttribute("activityAnnexErrorMsg", "附件上传失败");
        }
        return "redirect:/teacher/toAddActivityDetail";
    }

    //上传申请学分附件
    @RequestMapping("/student/uploadApplyAnnex")
    public String uploadApplyAnnex(ApplyScore applyScore,@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request, Model model, HttpSession session) throws IOException, IOException {
        System.out.println("上传申请学分附件"+applyScore);


        //获取文件名 : file.getOriginalFilename();
        String uploadFileName = file.getOriginalFilename();

        //如果文件名为空，直接回到首页！
        if ("".equals(uploadFileName)) {
            model.addAttribute("allMsgShow", "ERROR");
            return "allMsgShow";
        }
        System.out.println("上传文件名 : " + uploadFileName);

        //上传路径保存设置
        String path = request.getServletContext().getRealPath("/upload/"+applyScore.getActivityNo());//
        File realPath = new File(path);
        if (!realPath.exists()) {
            realPath.mkdir();
        }
        System.out.println("上传文件保存地址：" + realPath);

        InputStream is = file.getInputStream(); //文件输入流
        OutputStream os = new FileOutputStream(new File(realPath, uploadFileName)); //文件输出流

        //读取写出
        int len = 0;
        byte[] buffer = new byte[1024];
        while ((len = is.read(buffer)) != -1) {
            os.write(buffer, 0, len);
            os.flush();
        }
        os.close();
        is.close();

        applyScore.setApplyAnnexName(uploadFileName);
        applyScore.setApplyAnnex("/upload/"+applyScore.getActivityNo()+"/"+ uploadFileName);

        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//可以方便地修改日期格式
        String time = dateFormat.format( now );
        applyScore.setApplyTime(time);
        applyScore.setAnswerStatus("T");
        System.out.println("学生申请学分"+applyScore);

        if (studentService.applyScoreWithAnnex(applyScore) != 0 && teacherService.updateAnswerStatus(applyScore)!=0) {
            model.addAttribute("allMsgShow", "CORRECT");

            //***************************************************************************************************
            //添加学生活动跟踪日志
            UserDiary userDiary=new UserDiary();
            userDiary.setUserOperate("申请活动"+applyScore.getActivityNo()+"学分");

            Date nowRecord = new Date();
            SimpleDateFormat dateFormatRecord = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//可以方便地修改日期格式
            String timeRecord = dateFormatRecord.format(nowRecord);
            userDiary.setUserOperateTime(timeRecord);

            Student studentRecord= (Student) session.getAttribute("studentData");
            userDiary.setUserNo(studentRecord.getStudentNo());

            String stuLoginTime= (String) session.getAttribute("stuLoginTime");
            userDiary.setUserLoginTime(stuLoginTime);
            if(studentService.stuOperateRecord(userDiary)!=0){
                System.out.println("申请活动"+applyScore.getActivityNo()+"学分已被成功记录"+timeRecord);
            }
            //***************************************************************************************************

        } else {
            model.addAttribute("allMsgShow", "ERROR");
        }
        return "allMsgShow";

    }

        //学生上传头像或者个人身份照
    @RequestMapping("/student/uploadPhoto")
    public String uploadStuPhoto(@RequestParam("fileType") String fileType,@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request, Model model, HttpSession session) throws IOException, IOException {


        Student student = (Student) session.getAttribute("studentData");
        student = studentService.findStudentByNo(student);

        //获取文件名 : file.getOriginalFilename();
        String uploadFileName = file.getOriginalFilename();

        //如果文件名为空，直接回到首页！
        if ("".equals(uploadFileName)) {
            model.addAttribute("allMsgShow", "Error");
            return "allMsgShow";//"redirect:/teacher/toAddActivityDetail";
        }
        System.out.println("上传文件名 : " + uploadFileName);

        //上传路径保存设置
        String path = request.getServletContext().getRealPath("/upload/" + student.getStudentNo());
        //如果路径不存在，创建一个
        File realPath = new File(path);
        if (!realPath.exists()) {
            realPath.mkdir();
        }
        System.out.println("上传文件保存地址：" + realPath);

        InputStream is = file.getInputStream(); //文件输入流
        OutputStream os = new FileOutputStream(new File(realPath, uploadFileName)); //文件输出流

        //读取写出
        int len = 0;
        byte[] buffer = new byte[1024];
        while ((len = is.read(buffer)) != -1) {
            os.write(buffer, 0, len);
            os.flush();
        }
        os.close();
        is.close();

        UserAvatar userAvatar = new UserAvatar();
        userAvatar.setUserNo(student.getStudentNo());

        if(fileType.contains("AvatarPhoto")){
            userAvatar.setAvatar("/upload/" + student.getStudentNo() + "/" + uploadFileName);
            userAvatar.setAvatarName(uploadFileName);

            //***************************************************************************************************
            //添加学生活动跟踪日志
            UserDiary userDiary=new UserDiary();
            userDiary.setUserOperate("更换头像");

            Date nowRecord = new Date();
            SimpleDateFormat dateFormatRecord = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//可以方便地修改日期格式
            String timeRecord = dateFormatRecord.format(nowRecord);
            userDiary.setUserOperateTime(timeRecord);

            Student studentRecord= (Student) session.getAttribute("studentData");
            userDiary.setUserNo(studentRecord.getStudentNo());

            String stuLoginTime= (String) session.getAttribute("stuLoginTime");
            userDiary.setUserLoginTime(stuLoginTime);
            if(studentService.stuOperateRecord(userDiary)!=0){
                System.out.println("更换头像已被成功记录"+timeRecord);
            }
            //***************************************************************************************************

        }else {
            userAvatar.setIDPhoto("/upload/" + student.getStudentNo() + "/" + uploadFileName);

            //***************************************************************************************************
            //添加学生活动跟踪日志
            UserDiary userDiary=new UserDiary();
            userDiary.setUserOperate("更换身份照");

            Date nowRecord = new Date();
            SimpleDateFormat dateFormatRecord = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//可以方便地修改日期格式
            String timeRecord = dateFormatRecord.format(nowRecord);
            userDiary.setUserOperateTime(timeRecord);

            Student studentRecord= (Student) session.getAttribute("studentData");
            userDiary.setUserNo(studentRecord.getStudentNo());

            String stuLoginTime= (String) session.getAttribute("stuLoginTime");
            userDiary.setUserLoginTime(stuLoginTime);
            if(studentService.stuOperateRecord(userDiary)!=0){
                System.out.println("更换身份照已被成功记录"+timeRecord);
            }
            //***************************************************************************************************
        }


        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//可以方便地修改日期格式
        String time = dateFormat.format(now);
        userAvatar.setChangeTime(time);
        userAvatar.setUploadTime(time);
        //判断是否已经初始化
        if (studentService.JudgeAvatar(userAvatar) == null) {
            System.out.println("头像未初始化");
            if (studentService.initializeAvatar(userAvatar) != 0) {
                System.out.println("头像初始化完成");

                if(fileType.contains("AvatarPhoto")){
                    if (studentService.uploadAvatar(userAvatar) != 0) {
                        System.out.println("头像上传完成");
                        model.addAttribute("allMsgShow", "Correct");
                    }
                }else {
                    if(studentService.uploadIdPhoto(userAvatar)!=0){
                        System.out.println("头像上传完成");
                        model.addAttribute("allMsgShow", "Correct");
                    }
                }


            }

        } else {

            if(fileType.contains("AvatarPhoto")){
                studentService.uploadAvatar(userAvatar);
            }else {
                studentService.uploadIdPhoto(userAvatar);
            }

            System.out.println("头像上传完成");
            model.addAttribute("allMsgShow", "Correct");
        }
        return "allMsgShow";

    }

    //教师上传头像或者个人身份照
    @RequestMapping("/teacher/uploadIdPhoto")
    public String uploadTeaPhoto(@RequestParam("fileType") String fileType,@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request, Model model, HttpSession session) throws IOException, IOException {


        Teacher teacher= (Teacher) session.getAttribute("teacher");
        teacher=teacherService.findTeacherByNo(teacher);

        //获取文件名 : file.getOriginalFilename();
        String uploadFileName = file.getOriginalFilename();

        //如果文件名为空，直接回到首页！
        if ("".equals(uploadFileName)) {
            model.addAttribute("allMsgShow", "Error");
            return "allMsgShow";//"redirect:/teacher/toAddActivityDetail";
        }
        System.out.println("上传文件名 : " + uploadFileName);

        //上传路径保存设置
        String path = request.getServletContext().getRealPath("/upload/" + teacher.getTeacherNo());
        //如果路径不存在，创建一个
        File realPath = new File(path);
        if (!realPath.exists()) {
            realPath.mkdir();
        }
        System.out.println("上传文件保存地址：" + realPath);

        InputStream is = file.getInputStream(); //文件输入流
        OutputStream os = new FileOutputStream(new File(realPath, uploadFileName)); //文件输出流

        //读取写出
        int len = 0;
        byte[] buffer = new byte[1024];
        while ((len = is.read(buffer)) != -1) {
            os.write(buffer, 0, len);
            os.flush();
        }
        os.close();
        is.close();

        UserAvatar userAvatar = new UserAvatar();
        userAvatar.setUserNo(teacher.getTeacherNo());

        if(fileType.contains("AvatarPhoto")){
            userAvatar.setAvatar("/upload/" + teacher.getTeacherNo() + "/" + uploadFileName);
            userAvatar.setAvatarName(uploadFileName);
        }else {
            userAvatar.setIDPhoto("/upload/" + teacher.getTeacherNo() + "/" + uploadFileName);
        }


        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//可以方便地修改日期格式
        String time = dateFormat.format(now);
        userAvatar.setChangeTime(time);
        userAvatar.setUploadTime(time);
        //判断是否已经初始化
        if (studentService.JudgeAvatar(userAvatar) == null) {
            System.out.println("头像未初始化");
            if (studentService.initializeAvatar(userAvatar) != 0) {
                System.out.println("头像初始化完成");

                if(fileType.contains("AvatarPhoto")){
                    if (studentService.uploadAvatar(userAvatar) != 0) {
                        System.out.println("头像上传完成");

                        //***************************************************************************************************
                        //添加教师活动跟踪日志
                        UserDiary userDiary=new UserDiary();
                        userDiary.setUserOperate("完善照片");

                        Date nowRecord = new Date();
                        SimpleDateFormat dateFormatRecord = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//可以方便地修改日期格式
                        String timeRecord = dateFormatRecord.format(nowRecord);
                        userDiary.setUserOperateTime(timeRecord);

                        Teacher teacherRecord= (Teacher) session.getAttribute("teacher");
                        userDiary.setUserNo(teacherRecord.getTeacherNo());

                        String teaLoginTime= (String) session.getAttribute("teaLoginTime");
                        userDiary.setUserLoginTime(teaLoginTime);
                        if(studentService.stuOperateRecord(userDiary)!=0){
                            System.out.println("完善照片已被成功记录"+timeRecord);
                        }
                        //***************************************************************************************************

                        model.addAttribute("allMsgShow", "Correct");
                    }
                }else {
                    if(studentService.uploadIdPhoto(userAvatar)!=0){
                        System.out.println("头像上传完成");

                        //***************************************************************************************************
                        //添加教师活动跟踪日志
                        UserDiary userDiary=new UserDiary();
                        userDiary.setUserOperate("完善照片");

                        Date nowRecord = new Date();
                        SimpleDateFormat dateFormatRecord = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//可以方便地修改日期格式
                        String timeRecord = dateFormatRecord.format(nowRecord);
                        userDiary.setUserOperateTime(timeRecord);

                        Teacher teacherRecord= (Teacher) session.getAttribute("teacher");
                        userDiary.setUserNo(teacherRecord.getTeacherNo());

                        String teaLoginTime= (String) session.getAttribute("teaLoginTime");
                        userDiary.setUserLoginTime(teaLoginTime);
                        if(studentService.stuOperateRecord(userDiary)!=0){
                            System.out.println("完善照片已被成功记录"+timeRecord);
                        }
                        //***************************************************************************************************

                        model.addAttribute("allMsgShow", "Correct");
                    }
                }


            }

        } else {

            if(fileType.contains("AvatarPhoto")){
                studentService.uploadAvatar(userAvatar);
            }else {
                studentService.uploadIdPhoto(userAvatar);
            }

            System.out.println("头像上传完成");

            //***************************************************************************************************
            //添加教师活动跟踪日志
            UserDiary userDiary=new UserDiary();
            userDiary.setUserOperate("完善照片");

            Date nowRecord = new Date();
            SimpleDateFormat dateFormatRecord = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//可以方便地修改日期格式
            String timeRecord = dateFormatRecord.format(nowRecord);
            userDiary.setUserOperateTime(timeRecord);

            Teacher teacherRecord= (Teacher) session.getAttribute("teacher");
            userDiary.setUserNo(teacherRecord.getTeacherNo());

            String teaLoginTime= (String) session.getAttribute("teaLoginTime");
            userDiary.setUserLoginTime(teaLoginTime);
            if(studentService.stuOperateRecord(userDiary)!=0){
                System.out.println("完善照片已被成功记录"+timeRecord);
            }
            //***************************************************************************************************

            model.addAttribute("allMsgShow", "Correct");
        }
        return "allMsgShow";

    }


    //管理员上传头像和身份照

    @RequestMapping("/admin/uploadIdPhoto")
    public String uploadadminPhoto(@RequestParam("fileType") String fileType,@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request, Model model, HttpSession session) throws IOException, IOException {

        Admin admin= (Admin) session.getAttribute("adminData");
        admin=adminService.findAdminByName(admin);

        //获取文件名 : file.getOriginalFilename();
        String uploadFileName = file.getOriginalFilename();

        //如果文件名为空，直接回到首页！
        if ("".equals(uploadFileName)) {
            model.addAttribute("allMsgShow", "Error");
            return "allMsgShow";//"redirect:/teacher/toAddActivityDetail";
        }
        System.out.println("上传文件名 : " + uploadFileName);

        //上传路径保存设置
        String path = request.getServletContext().getRealPath("/upload/" + admin.getAdminName());
        //如果路径不存在，创建一个
        File realPath = new File(path);
        if (!realPath.exists()) {
            realPath.mkdir();
        }
        System.out.println("上传文件保存地址：" + realPath);

        InputStream is = file.getInputStream(); //文件输入流
        OutputStream os = new FileOutputStream(new File(realPath, uploadFileName)); //文件输出流

        //读取写出
        int len = 0;
        byte[] buffer = new byte[1024];
        while ((len = is.read(buffer)) != -1) {
            os.write(buffer, 0, len);
            os.flush();
        }
        os.close();
        is.close();

        UserAvatar userAvatar = new UserAvatar();
        userAvatar.setUserNo(admin.getAdminName());

        if(fileType.contains("AvatarPhoto")){
            userAvatar.setAvatar("/upload/" + admin.getAdminName() + "/" + uploadFileName);
            userAvatar.setAvatarName(uploadFileName);
        }else {
            userAvatar.setIDPhoto("/upload/" + admin.getAdminName() + "/" + uploadFileName);
        }


        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//可以方便地修改日期格式
        String time = dateFormat.format(now);
        userAvatar.setChangeTime(time);
        userAvatar.setUploadTime(time);
        //判断是否已经初始化
        if (studentService.JudgeAvatar(userAvatar) == null) {
            System.out.println("头像未初始化");
            if (studentService.initializeAvatar(userAvatar) != 0) {
                System.out.println("头像初始化完成");

                if(fileType.contains("AvatarPhoto")){
                    if (studentService.uploadAvatar(userAvatar) != 0) {
                        System.out.println("头像上传完成");

                        //***************************************************************************************************
                        //添加管理员活动跟踪日志
                        UserDiary userDiary=new UserDiary();
                        userDiary.setUserOperate("更新照片");

                        Date nowRecord = new Date();
                        SimpleDateFormat dateFormatRecord = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//可以方便地修改日期格式
                        String timeRecord = dateFormatRecord.format(nowRecord);
                        userDiary.setUserOperateTime(timeRecord);

                        Admin adminRecord= (Admin) session.getAttribute("adminData");
                        userDiary.setUserNo(adminRecord.getAdminName());

                        String teaLoginTime= (String) session.getAttribute("adminLoginTime");
                        userDiary.setUserLoginTime(teaLoginTime);
                        if(studentService.stuOperateRecord(userDiary)!=0){
                            System.out.println("更新照片已被成功记录"+timeRecord);
                        }
                        //***************************************************************************************************

                        model.addAttribute("allMsgShow", "Correct");
                    }
                }else {
                    if(studentService.uploadIdPhoto(userAvatar)!=0){
                        System.out.println("头像上传完成");

                        //***************************************************************************************************
                        //添加管理员活动跟踪日志
                        UserDiary userDiary=new UserDiary();
                        userDiary.setUserOperate("更新照片");

                        Date nowRecord = new Date();
                        SimpleDateFormat dateFormatRecord = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//可以方便地修改日期格式
                        String timeRecord = dateFormatRecord.format(nowRecord);
                        userDiary.setUserOperateTime(timeRecord);

                        Admin adminRecord= (Admin) session.getAttribute("adminData");
                        userDiary.setUserNo(adminRecord.getAdminName());

                        String teaLoginTime= (String) session.getAttribute("adminLoginTime");
                        userDiary.setUserLoginTime(teaLoginTime);
                        if(studentService.stuOperateRecord(userDiary)!=0){
                            System.out.println("更新照片已被成功记录"+timeRecord);
                        }
                        //***************************************************************************************************

                        model.addAttribute("allMsgShow", "Correct");
                    }
                }


            }

        } else {

            if(fileType.contains("AvatarPhoto")){
                studentService.uploadAvatar(userAvatar);
            }else {
                studentService.uploadIdPhoto(userAvatar);
            }

            System.out.println("头像上传完成");

            //***************************************************************************************************
            //添加管理员活动跟踪日志
            UserDiary userDiary=new UserDiary();
            userDiary.setUserOperate("更新照片");

            Date nowRecord = new Date();
            SimpleDateFormat dateFormatRecord = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//可以方便地修改日期格式
            String timeRecord = dateFormatRecord.format(nowRecord);
            userDiary.setUserOperateTime(timeRecord);

            Admin adminRecord= (Admin) session.getAttribute("adminData");
            userDiary.setUserNo(adminRecord.getAdminName());

            String teaLoginTime= (String) session.getAttribute("adminLoginTime");
            userDiary.setUserLoginTime(teaLoginTime);
            if(studentService.stuOperateRecord(userDiary)!=0){
                System.out.println("更新照片已被成功记录"+timeRecord);
            }
            //***************************************************************************************************

            model.addAttribute("allMsgShow", "Correct");
        }
        return "allMsgShow";

    }

        //编写Controller
    /*
     * 采用file.Transto 来保存上传的文件
     */
    @RequestMapping("/upload2")
    public String fileUpload2(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {

        //上传路径保存设置
        String path = request.getServletContext().getRealPath("/upload");
        File realPath = new File(path);
        if (!realPath.exists()) {
            realPath.mkdir();
        }
        //上传文件地址
        System.out.println("上传文件保存地址：" + realPath);

        //通过CommonsMultipartFile的方法直接写文件（注意这个时候）
        file.transferTo(new File(realPath + "/" + file.getOriginalFilename()));

        return "redirect:/index.jsp";
    }


    @RequestMapping(value = "/download")
    public String downloads(HttpServletResponse response, HttpServletRequest request) throws Exception {
        //要下载的图片地址
        String path = request.getServletContext().getRealPath("/upload");
        String fileName = "基础语法.jpg";

        //1、设置response 响应头
        response.reset(); //设置页面不缓存,清空buffer
        response.setCharacterEncoding("UTF-8"); //字符编码
        response.setContentType("multipart/form-data"); //二进制传输数据
        //设置响应头
        response.setHeader("Content-Disposition",
                "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));

        File file = new File(path, fileName);
        //2、 读取文件--输入流
        InputStream input = new FileInputStream(file);
        //3、 写出文件--输出流
        OutputStream out = response.getOutputStream();

        byte[] buff = new byte[1024];
        int index = 0;
        //4、执行 写出操作
        while ((index = input.read(buff)) != -1) {
            out.write(buff, 0, index);
            out.flush();
        }
        out.close();
        input.close();
        return null;
    }

    //下载活动文件
    @RequestMapping(value = "/user/downloadActivityDetail")
    public void downloadActivityDetail(@RequestParam("fileType") String fileType,@RequestParam("activityNo") String activityNo, HttpServletResponse response, HttpServletRequest request, Model model) throws Exception {

        Activity activity=new Activity();
        activity.setActivityNo(activityNo);
        ActivityDescription activityDescription=teacherService.findActivityDescriptionByNo(activity);

        String fileName="";
        if(fileType.contains("annex")){
            fileName=activityDescription.getAnnexName();
        }else {
            fileName=activityDescription.getPhotoName();
        }


        //要下载的图片地址
        String path = request.getServletContext().getRealPath("/upload/"+activityNo);
        //String fileName = "基础语法.jpg";

        //1、设置response 响应头
        response.reset(); //设置页面不缓存,清空buffer
        response.setCharacterEncoding("UTF-8"); //字符编码
        response.setContentType("multipart/form-data"); //二进制传输数据
        //设置响应头
        response.setHeader("Content-Disposition",
                "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));

        File file = new File(path, fileName);
        //2、 读取文件--输入流
        InputStream input = new FileInputStream(file);
        //3、 写出文件--输出流
        OutputStream out = response.getOutputStream();

        byte[] buff = new byte[1024];
        int index = 0;
        //4、执行 写出操作
        while ((index = input.read(buff)) != -1) {
            out.write(buff, 0, index);
            out.flush();
        }
        out.close();
        input.close();
    }

    //下载学生申请学分附件
    @RequestMapping("/user/downloadApplyAnnex")
    public void downloadApplyAnnex(ApplyScore applyScore, HttpServletResponse response, HttpServletRequest request, Model model) throws Exception {

        String fileName=applyScore.getApplyAnnexName();

        //要下载的图片地址
        String path = request.getServletContext().getRealPath("/upload/"+applyScore.getActivityNo());
        //String fileName = "基础语法.jpg";

        //1、设置response 响应头
        response.reset(); //设置页面不缓存,清空buffer
        response.setCharacterEncoding("UTF-8"); //字符编码
        response.setContentType("multipart/form-data"); //二进制传输数据
        //设置响应头
        response.setHeader("Content-Disposition",
                "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));

        File file = new File(path, fileName);
        //2、 读取文件--输入流
        InputStream input = new FileInputStream(file);
        //3、 写出文件--输出流
        OutputStream out = response.getOutputStream();

        byte[] buff = new byte[1024];
        int index = 0;
        //4、执行 写出操作
        while ((index = input.read(buff)) != -1) {
            out.write(buff, 0, index);
            out.flush();
        }
        out.close();
        input.close();
    }
}